package org.jypj.dev.controller;

import org.jypj.dev.dao.IMacDao;
import org.jypj.dev.listener.SessionListener;
import org.jypj.dev.model.Menu;
import org.jypj.dev.model.User;
import org.jypj.dev.service.ICodeDataService;
import org.jypj.dev.service.IMenuService;
import org.jypj.dev.service.IUserService;
import org.jypj.dev.util.MD5Utils;
import org.jypj.dev.util.PropertyUtil;
import org.jypj.dev.util.StringUtil;
import org.jypj.dev.vo.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chenyuyuyu on 2017/3/26.
 */
@Controller
@RequestMapping(value = "safe")
public class WebApiController {

    @Resource
    private IMacDao macDao;

    @Resource
    private IUserService userService;

    @Resource
    private ICodeDataService codeDataService;

    @Resource
    private IMenuService menuService;

    /**
     * 登录接口
     * 0表示成功
     *
     * @param token
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "login")
    public Result login(String token, String macAddress, HttpSession session) {
        Result result = new Result();
        User user = new User();
        System.out.println("token=" + token);
        System.out.println("macAddressMd5=" + macAddress);
        try {
            String md5s = macDao.selectMacMd5();
            user.setToken(token);
            User user1 = userService.selectObjectByUser(user);
            if (null == user1 || StringUtil.isEmpty(token)) {
                result.setCode(-2);
                result.setMsg("用户名或者密码错误");
                return result;
            }
            if (!md5s.contains(macAddress) || StringUtil.isEmpty(macAddress)) {
                result.setCode(-3);
                result.setMsg("该客户机未授权");
                return result;
            }
            session.setAttribute("user", user1);
            System.out.println(MD5Utils.md5Encrypt(user1.getUserNum() + macAddress));
            SessionListener.sessionMap.put(MD5Utils.md5Encrypt(user1.getUserNum() + macAddress), session);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setMsg("网络异常");
            result.setExcMsg(e.toString());
        }
        return result;
    }

    /**
     * 跳转到首页
     *
     * @param key     userNum+macAddress ->MD5加密 32位小写
     * @param session
     * @return
     */
    @RequestMapping(value = "/{key}")
    public String home(@PathVariable String key, HttpSession session) {
        try {
            System.out.println("key=" + key);
            //首先验证登录的session是否存在
            HttpSession httpSession = SessionListener.sessionMap.get(key);
            if (null == httpSession) {
                return "noauth";
            }
            //存在就将user存到浏览器创建的session中
            User user = (User) httpSession.getAttribute("user");
            session.setAttribute("user", user);
            //将原来的session注销并移除
            SessionListener.forceLogoutSessionMapUser(key);
            //将通过浏览器创建的session存放在新的map中用户移除
            SessionListener.realSessionMap.put(key, session);
            //如果没有角色 也无权访问
            if (StringUtil.isEmpty(user.getRoleType())) {
                return "noauth";
            }
            //得到角色名称
            String roleName = codeDataService.selectItemTextByItemValue("jsgl", user.getRoleType());
            user.setRoleName(roleName);
            //设置菜单
            Map<String, Object> queryMap = new HashMap<>();
            List<Menu> menus = null;
            if (!"0000".equals(user.getRoleType())) {
                queryMap.put("roleType", user.getRoleType());
            }
            menus = menuService.selectAllByMap(queryMap);
            //如果该角色没有菜单就提示无权访问
            if (menus == null || menus.size() == 0) {
                return "noauth";
            }
            user.setMenus(menus);
            String fileServerUrl = PropertyUtil.getProperties("file_server_url");
            session.setAttribute("fileServerUrl", fileServerUrl);

        } catch (Exception e) {
            e.printStackTrace();
            return "noauth";
        }
        return "redirect:toMain.action";
    }

    @RequestMapping(value = "/toMain.action")
    public String toMain(HttpServletRequest request) {


        return "back/main";
    }

    /**
     * 判断链接是否一致在建立
     * 客户端每5分钟调用一次
     *
     * @return
     */
    @RequestMapping(value = "checkConn")
    @ResponseBody
    public Result checkConn(String key) {
        Result result = new Result();
        result.setParamNames("key");
        SessionListener.timeMap.put(key, new Date().getTime());
        return result;
    }

    /**
     * 注销登录
     *
     * @param key
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "logout")
    public Result logout(String key) {
        Result result = new Result();
        result.setParamNames("key");
        try {
            SessionListener.forceLogoutRealSessionMapUser(key);
            SessionListener.timeMap.remove(key);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(-1);
            result.setMsg("网络异常");
            result.setExcMsg(e.toString());
        }
        return result;
    }
}
